package com.linyaonan.leetcode.medium._155;

import java.util.LinkedList;
import java.util.Stack;

class MinStack {

    private LinkedList<Integer> stack;

    private Integer min = null;
    
    /** initialize your data structure here. */
    public MinStack() {
        this.stack = new LinkedList<>();
    }
    
    public void push(int x) {
        if (min == null) {
            min = x;
        }
        if (min > x) {
            min = x;
        }
        // 压入小值
        stack.push(min);
        stack.push(x);
    }
    
    public void pop() {
        stack.pop();
        int thisMin = stack.pop();
        // 重置min
        if (thisMin == min) {
            if (stack.size() >= 2) {
                min = getMin();
            } else {
                min = null;
            }
        }
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return stack.get(stack.size() - 2);
    }
}